package com.face.console.tools.filter;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * Description: AJAX请求跨域
 * <p>
 * Created by Andy_Lau on 2020/12/12 23:59
 */
@WebFilter(filterName = "authFilter", urlPatterns = "/*")
public class CorsConfigFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        System.out.println("拦截到请求地址："+request.getRequestURL());
        StringBuffer a = request.getRequestURL();
       String b = request.getHeader("Content-Type");
        if (StringUtils.isNotBlank(b)) {
            System.out.println(" 当前接口请求格式 为："+b);
        }

        response.addHeader("Access-Control-Allow-Credentials", "true");
       response.addHeader("Access-Control-Allow-Origin", "*");
       response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
       response.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
        if (request.getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            return;
        }
        filterChain.doFilter(request,response);
    }

    @Override
    public void destroy() {

    }
}
